<script setup lang="ts">
  import routeComponentName from '@/config/route-component-name'
  import {
    ElInput,
    ElIcon,
    ElTable,
    ElTableColumn,
    TableInstance,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElMessageBox,
  } from 'element-plus'
  import { Search, ArrowDown } from '@element-plus/icons-vue'
  import Pagination from '@/components/Pagination/index.vue'
  import {
    useGetEnterpriseNoticeList,
    useEnterpriseNoticeEnableByIds,
    useEnterpriseNoticeDisableByIds,
    useEnterpriseNoticeTopUpByIds,
    useEnterpriseNoticeUnTopUpByIds,
    useEnterpriseNoticeDelByIds,
  } from '@/services/pages/enterprise-notice/useEnterpriseNotice'
  import { onMounted, ref, watch } from 'vue'
  import UpdateVisibleTypeModal from './components/UpdateVisibleTypeModal.vue'
  import { MultipleOperate } from './types'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useRoute, useRouter } from 'vue-router'

  const { total, getListParam, getListLoading, enterpriseNoticeList, getList } =
    useGetEnterpriseNoticeList()
  const { enable } = useEnterpriseNoticeEnableByIds()
  const { disable } = useEnterpriseNoticeDisableByIds()
  const { topUp } = useEnterpriseNoticeTopUpByIds()
  const { unTopUp } = useEnterpriseNoticeUnTopUpByIds()
  const { del } = useEnterpriseNoticeDelByIds()

  defineOptions({
    name: routeComponentName.enterpriseNotice.enterpriseNoticeList,
  })

  // 激活路由对象
  const route = useRoute()

  // 全局路由对象
  const router = useRouter()

  // 选择的公告id集合
  const selectedIds = ref<Array<string>>([])

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 更新可见类型弹窗
  const updateVisibleTypeModalVisible = ref(false)

  /**
   * 获取列表方法
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 获取消息弹出框的正文内容
   * @param {('enable'|'disable'|'del'|'topUp'|'unTopUp')} type - 操作类型
   */
  const getGetElMessageBoxMsgOption = (
    type: 'enable' | 'disable' | 'del' | 'topUp' | 'unTopUp',
  ) => {
    const msgOption = {
      enable: '确定要启用选中的公告？',
      disable: '确定要禁用选中的公告？',
      del: '确定要删除选中的公告？',
      topUp: '确定要置顶选中的公告？',
      unTopUp: '确定要取消置顶选中的公告？',
    }
    return msgOption[type]
  }

  /**
   * 调用批量操作方法
   * @param {('enable'|'disable'|'del'|'topUp'|'unTopUp')} type - 操作类型
   */
  const multipleOperateCall = async (type: 'enable' | 'disable' | 'del' | 'topUp' | 'unTopUp') => {
    if (type === 'enable') {
      return await enable(selectedIds.value)
    }

    if (type === 'disable') {
      return await disable(selectedIds.value)
    }

    if (type === 'del') {
      return await del(selectedIds.value)
    }

    if (type === 'topUp') {
      return await topUp(selectedIds.value)
    }

    if (type === 'unTopUp') {
      return await unTopUp(selectedIds.value)
    }
  }

  /**
   * 批量操作
   * @param {MultipleOperate} type - 操作类型
   */
  const handleMultipleOperate = (type: MultipleOperate) => {
    if (selectedIds.value.length <= 0) {
      HMessageBox.error('请选择公告')
      return
    }

    if (type === 'updateVisibleType') {
      updateVisibleTypeModalVisible.value = true
      return
    }

    ElMessageBox({
      title: '提示',
      message: getGetElMessageBoxMsgOption(type),
      type: 'warning',
      showCancelButton: true,
      autofocus: false,
      async beforeClose(action, instance, done) {
        if (['cancel', 'close'].includes(action)) {
          done()
          return
        }

        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          const res = await multipleOperateCall(type)
          instance.confirmButtonLoading = false
          if (res.code === 20000) {
            done()
            HMessage.success('更新成功')
            _getList()
            return
          }
          HMessageBox.error(res.message)
        }
      },
    })
  }

  /**
   * 企业公告选择事件
   * @param {Array<EnterpriseNoticeItem>} enterpriseNoticeList - 公告列表
   */
  const handleEnterpriseNoticeSelect = (enterpriseNoticeList: Array<EnterpriseNoticeItem>) => {
    selectedIds.value = enterpriseNoticeList.map((item) => item.id)
  }

  /**
   * 表格行删除、置顶点击事件
   * @param {EnterpriseNoticeItem} enterpriseNotice - 企业公告
   * @param {('del'|'topUp')} type - 操作类型
   */
  const handleTableCellClick = (enterpriseNotice: EnterpriseNoticeItem, type: 'del' | 'topUp') => {
    if (tableInstance.value) {
      tableInstance.value.toggleRowSelection(enterpriseNotice, true)
      ElMessageBox({
        title: '提示',
        message: type === 'del' ? '确定要删除该公告？' : '确定要置顶该公告？',
        showCancelButton: true,
        autofocus: false,
        type: type === 'del' ? 'error' : 'warning',
        async beforeClose(action, instance, done) {
          if (['close', 'cancel'].includes(action)) {
            done()
            return
          }

          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            const apiOption = {
              del: del,
              topUp: topUp,
            }
            const res = await apiOption[type](selectedIds.value)
            instance.confirmButtonLoading = false
            if (res.code === 20000) {
              HMessage.success(type === 'del' ? '删除成功' : '置顶成功')
              _getList()
              done()
              return
            }
            HMessageBox.error(res.message)
          }
        },
      })
    }
  }

  const onUpdate = (id: string) => {
    router.push({ path: `/enterprise/notice/update/${id}` })
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'enterpriseNoticeList' && route.query.isUpdate === '1') {
        _getList()
      }
    },
    { immediate: true },
  )

  onMounted(() => {
    _getList()
  })
</script>

<template>
  <div v-loading="getListLoading" class="enterprise-notice-list-wrapper">
    <div class="enterprise-notice-list">
      <div class="header">
        <div class="btn-group">
          <router-link to="/enterprise/notice/create">
            <h-plain-button v-permission="'notice_add'" > 创建公告 </h-plain-button>
          </router-link>
          <el-dropdown trigger="click">
            <h-button :disabled="selectedIds.length <= 0">
              批量操作
              <el-icon>
                <arrow-down></arrow-down>
              </el-icon>
            </h-button>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-permission="'notice_enabled'" >
                  <el-dropdown-item @click="handleMultipleOperate('enable')">启用</el-dropdown-item>
                </div>
                <div v-permission="'notice_disabled'">
                  <el-dropdown-item @click="handleMultipleOperate('disable')">禁用</el-dropdown-item>
                </div>
                <div v-permission="'notice_delete'">
                  <el-dropdown-item @click="handleMultipleOperate('del')">删除</el-dropdown-item>
                </div>
                <div v-permission="'notice_top'">
                  <el-dropdown-item @click="handleMultipleOperate('topUp')">置顶</el-dropdown-item>
                </div>
                <div v-permission="'notice_untop'">
                  <el-dropdown-item @click="handleMultipleOperate('unTopUp')"
                  >不置顶</el-dropdown-item
                >
                </div>
                <div v-permission="'notice_visible'">
                  <el-dropdown-item @click="handleMultipleOperate('updateVisibleType')"
                  >修改可见类型</el-dropdown-item
                >
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search-wrapper">
          <el-input
            v-model.trim="getListParam.name"
            placeholder="搜索关键字"
            clearable
            @clear="_getList"
            @keyup.enter="_getList"
          />
          <h-button type="primary" @click="_getList">
            <el-icon>
              <search></search>
            </el-icon>
            搜索
          </h-button>
        </div>
      </div>
      <div class="table">
        <el-table
          ref="tableInstance"
          :border="true"
          stripe
          height="100%"
          :data="enterpriseNoticeList"
          @selection-change="handleEnterpriseNoticeSelect"
        >
          <el-table-column
            width="50"
            :align="'center'"
            fixed="left"
            type="selection"
          ></el-table-column>
          <el-table-column
            width="50"
            :align="'center'"
            fixed="left"
            label="序号"
            type="index"
          ></el-table-column>
          <el-table-column width="150" label="公告标题" prop="name" show-overflow-tooltip>
            <template #default="{ row }">
              <h-link @click="onUpdate(row.id)">{{ row.name }}</h-link>
            </template>
          </el-table-column>
          <el-table-column width="100" label="发布人" prop="createEmp"></el-table-column>
          <el-table-column width="140" label="发布时间" prop="createTime"></el-table-column>
          <el-table-column width="140" label="修改时间" prop="updateTime"></el-table-column>
          <el-table-column width="80" label="是否置顶">
            <template #default="{ row }">
              {{ row.topUp ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column width="100" label="可见类型">
            <template #default="{ row }">
              <span v-if="row.visibilityType === 1">全部可见</span>
              <span v-else-if="row.visibilityType === 2">网点可见</span>
              <span v-else>公司可见</span>
            </template>
          </el-table-column>
          <el-table-column width="70" label="状态" fixed="right" :align="'center'">
            <template #default="{ row }">
              <div class="flex_justify_center">
                <h-status v-if="row.status" type="info">禁用</h-status>
                <h-status v-else>启用</h-status>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="140" label="操作" fixed="right">
            <template #default="{ row }">
              <h-space>
                <h-link v-permission="'notice_update'" @click="onUpdate(row.id)">编辑</h-link>
                <h-link v-permission="'notice_delete'" type="error" @click="handleTableCellClick(row, 'del')">删除</h-link>
                <h-link v-permission="'notice_top'"  @click="handleTableCellClick(row, 'topUp')">置顶</h-link>
              </h-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginationInstance"
          :list_total="total"
          @size-change="_getList"
          @current-change="_getList"
        ></Pagination>
      </div>
    </div>

    <update-visible-type-modal
      v-model:visible="updateVisibleTypeModalVisible"
      :select-ids="selectedIds"
      @update="_getList"
    ></update-visible-type-modal>
  </div>
</template>

<style scoped lang="scss">
  .enterprise-notice-list-wrapper {
    width: 100%;
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .enterprise-notice-list {
      width: 100%;
      height: 100%;
      background-color: #fff;
      display: flex;
      padding: 12px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .header {
        width: 100%;
        display: flex;
        justify-content: space-between;

        .btn-group {
          display: flex;
          column-gap: 5px;
        }

        .search-wrapper {
          display: flex;
          column-gap: 5px;
        }
      }

      .table {
        max-height: calc(100% - 80px);
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
